document.addEventListener('DOMContentLoaded', () => {
    const backToPopupButton = document.getElementById('backToPopup');
    if (backToPopupButton) {
        backToPopupButton.addEventListener('click', () => {
            window.location.href = 'popup.html';
        });
    }

    // Simple XOR encryption/decryption for demonstration
    const encryptDecrypt = (text, key) => {
        let result = '';
        for (let i = 0; i < text.length; i++) {
            result += String.fromCharCode(text.charCodeAt(i) ^ key.charCodeAt(i % key.length));
        }
        return result;
    };

    const saveSensitiveData = async (data, key) => {
        try {
            if (typeof chrome === 'undefined' || !chrome.storage) {
                console.log('Chrome storage API not available (running in browser)');
                return false;
            }
            const encryptedData = encryptDecrypt(data, key);
            await chrome.storage.local.set({sensitiveData: encryptedData});
            console.log('Sensitive data saved (encrypted).');
            return true;
        } catch (error) {
            console.error('Error saving sensitive data:', error);
            return false;
        }
    };

    const loadSensitiveData = async (key) => {
        try {
            if (typeof chrome === 'undefined' || !chrome.storage) {
                console.log('Chrome storage API not available (running in browser)');
                return null;
            }
            const result = await chrome.storage.local.get(['sensitiveData']);
            if (result.sensitiveData) {
                const decryptedData = encryptDecrypt(result.sensitiveData, key);
                console.log('Sensitive data loaded (decrypted):', decryptedData);
                return decryptedData;
            }
            return null;
        } catch (error) {
            console.error('Error loading sensitive data:', error);
            return null;
        }
    };

    // Example usage (assuming input field with id 'sensitiveInput' and button 'saveSensitiveButton')
    const sensitiveInput = document.getElementById('sensitiveInput');
    const saveSensitiveButton = document.getElementById('saveSensitiveButton');
    const displaySensitiveData = document.getElementById('displaySensitiveData');

    if (saveSensitiveButton && sensitiveInput && displaySensitiveData) {
        saveSensitiveButton.addEventListener('click', async () => {
            const dataToSave = sensitiveInput.value;
            if (!dataToSave.trim()) {
                displaySensitiveData.textContent = 'Please enter some data to save.';
                return;
            }
            const encryptionKey = 'mySuperSecretKey'; // In a real app, this key should be securely managed
            const saved = await saveSensitiveData(dataToSave, encryptionKey);
            if (saved) {
                sensitiveInput.value = ''; // Clear input after saving
                // Reload and display the saved data
                const loadedData = await loadSensitiveData(encryptionKey);
                displaySensitiveData.textContent = loadedData ? `Loaded: ${loadedData}` : 'No data saved.';
            } else {
                displaySensitiveData.textContent = 'Failed to save data (Chrome extension API not available).';
            }
        });

        // Load data when the settings page opens
        const encryptionKey = 'mySuperSecretKey';
        loadSensitiveData(encryptionKey).then(loadedData => {
            displaySensitiveData.textContent = loadedData ? `Loaded: ${loadedData}` : 'No data saved.';
        });
    }

    // ===== Smart Categorization Functionality =====

    // Default categorization settings
    const defaultCategorizationSettings = {
        enabled: false,
        fileTypeRules: [
            {extensions: ['.pdf', '.doc', '.docx', '.txt'], category: 'Documents'},
            {extensions: ['.mp4', '.avi', '.mkv', '.mov'], category: 'Videos'},
            {extensions: ['.mp3', '.wav', '.flac', '.aac'], category: 'Audio'},
            {extensions: ['.jpg', '.jpeg', '.png', '.gif', '.bmp'], category: 'Images'},
            {extensions: ['.zip', '.rar', '.7z', '.tar'], category: 'Archives'}
        ],
        customTags: ['Work', 'Personal', 'Important', 'Archive']
    };

    // Save categorization settings
    const saveCategorizationSettings = async (settings) => {
        try {
            if (typeof chrome === 'undefined' || !chrome.storage) {
                console.log('Chrome storage API not available (running in browser)');
                return false;
            }
            await chrome.storage.local.set({categorizationSettings: settings});
            console.log('Categorization settings saved.');
            return true;
        } catch (error) {
            console.error('Error saving categorization settings:', error);
            return false;
        }
    };

    // Load categorization settings
    const loadCategorizationSettings = async () => {
        try {
            if (typeof chrome === 'undefined' || !chrome.storage) {
                console.log('Chrome storage API not available (running in browser)');
                return defaultCategorizationSettings;
            }
            const result = await chrome.storage.local.get(['categorizationSettings']);
            return result.categorizationSettings || defaultCategorizationSettings;
        } catch (error) {
            console.error('Error loading categorization settings:', error);
            return defaultCategorizationSettings;
        }
    };

    // Create file type rule element
    const createFileTypeRuleElement = (rule, index) => {
        const ruleDiv = document.createElement('div');
        ruleDiv.className = 'file-type-rule';
        ruleDiv.innerHTML = `
      <input type="text" value="${rule.extensions.join(', ')}" placeholder="File extensions (e.g., .pdf, .doc)" />
      <select>
        <option value="Documents" ${rule.category === 'Documents' ? 'selected' : ''}>Documents</option>
        <option value="Videos" ${rule.category === 'Videos' ? 'selected' : ''}>Videos</option>
        <option value="Audio" ${rule.category === 'Audio' ? 'selected' : ''}>Audio</option>
        <option value="Images" ${rule.category === 'Images' ? 'selected' : ''}>Images</option>
        <option value="Archives" ${rule.category === 'Archives' ? 'selected' : ''}>Archives</option>
        <option value="Software" ${rule.category === 'Software' ? 'selected' : ''}>Software</option>
        <option value="Other" ${rule.category === 'Other' ? 'selected' : ''}>Other</option>
      </select>
      <button onclick="removeFileTypeRule(${index})">Remove</button>
    `;
        return ruleDiv;
    };

    // Create custom tag element
    const createCustomTagElement = (tag, index) => {
        const tagSpan = document.createElement('span');
        tagSpan.className = 'custom-tag';
        tagSpan.innerHTML = `
      ${tag}
      <button class="remove-tag" onclick="removeCustomTag(${index})">×</button>
    `;
        return tagSpan;
    };

    // Render file type rules
    const renderFileTypeRules = (rules) => {
        const container = document.getElementById('fileTypeRules');
        if (!container) return;

        container.innerHTML = '';
        rules.forEach((rule, index) => {
            container.appendChild(createFileTypeRuleElement(rule, index));
        });
    };

    // Render custom tags
    const renderCustomTags = (tags) => {
        const container = document.getElementById('customTags');
        if (!container) return;

        container.innerHTML = '';
        tags.forEach((tag, index) => {
            container.appendChild(createCustomTagElement(tag, index));
        });
    };

    // Global functions for removing rules and tags
    window.removeFileTypeRule = (index) => {
        currentSettings.fileTypeRules.splice(index, 1);
        renderFileTypeRules(currentSettings.fileTypeRules);
    };

    window.removeCustomTag = (index) => {
        currentSettings.customTags.splice(index, 1);
        renderCustomTags(currentSettings.customTags);
    };

    // Current settings state
    let currentSettings = {...defaultCategorizationSettings};

    // Initialize smart categorization UI
    const initSmartCategorization = async () => {
        const enableCheckbox = document.getElementById('enableCategorization');
        const settingsDiv = document.getElementById('categorizationSettings');
        const addRuleButton = document.getElementById('addFileTypeRule');
        const addTagButton = document.getElementById('addTagButton');
        const newTagInput = document.getElementById('newTagInput');
        const saveButton = document.getElementById('saveCategorization');
        const resetButton = document.getElementById('resetCategorization');

        if (!enableCheckbox || !settingsDiv) return;

        // Load current settings
        currentSettings = await loadCategorizationSettings();

        // Set initial state
        enableCheckbox.checked = currentSettings.enabled;
        settingsDiv.style.display = currentSettings.enabled ? 'block' : 'none';

        // Render initial rules and tags
        renderFileTypeRules(currentSettings.fileTypeRules);
        renderCustomTags(currentSettings.customTags);

        // Enable/disable toggle
        enableCheckbox.addEventListener('change', () => {
            currentSettings.enabled = enableCheckbox.checked;
            settingsDiv.style.display = currentSettings.enabled ? 'block' : 'none';
        });

        // Add file type rule
        if (addRuleButton) {
            addRuleButton.addEventListener('click', () => {
                currentSettings.fileTypeRules.push({
                    extensions: ['.ext'],
                    category: 'Other'
                });
                renderFileTypeRules(currentSettings.fileTypeRules);
            });
        }

        // Add custom tag
        if (addTagButton && newTagInput) {
            const addTag = () => {
                const tagName = newTagInput.value.trim();
                if (tagName && !currentSettings.customTags.includes(tagName)) {
                    currentSettings.customTags.push(tagName);
                    renderCustomTags(currentSettings.customTags);
                    newTagInput.value = '';
                }
            };

            addTagButton.addEventListener('click', addTag);
            newTagInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    addTag();
                }
            });
        }

        // Save settings
        if (saveButton) {
            saveButton.addEventListener('click', async () => {
                // Update rules from UI
                const ruleElements = document.querySelectorAll('.file-type-rule');
                currentSettings.fileTypeRules = Array.from(ruleElements).map(element => {
                    const extensionsInput = element.querySelector('input[type="text"]');
                    const categorySelect = element.querySelector('select');
                    return {
                        extensions: extensionsInput.value.split(',').map(ext => ext.trim()).filter(ext => ext),
                        category: categorySelect.value
                    };
                });

                const saved = await saveCategorizationSettings(currentSettings);
                if (saved) {
                    alert('Categorization settings saved successfully!');
                } else {
                    alert('Failed to save settings (Chrome extension API not available).');
                }
            });
        }

        // Reset to default
        if (resetButton) {
            resetButton.addEventListener('click', () => {
                if (confirm('Are you sure you want to reset to default settings?')) {
                    currentSettings = {...defaultCategorizationSettings};
                    enableCheckbox.checked = currentSettings.enabled;
                    settingsDiv.style.display = currentSettings.enabled ? 'block' : 'none';
                    renderFileTypeRules(currentSettings.fileTypeRules);
                    renderCustomTags(currentSettings.customTags);
                }
            });
        }
    };

    // Initialize smart categorization when DOM is ready
    initSmartCategorization();

    // ===== File Verification Functionality =====

    // Default file verification settings
    const defaultFileVerificationSettings = {
        enabled: false,
        verificationTypes: {
            md5: true,
            sha1: false,
            sha256: true,
            sizeCheck: true
        },
        failureAction: 'warn', // 'warn', 'block', 'retry'
        timeout: 30, // seconds
        enableLogs: true,
        autoVerifyLargeFiles: true
    };

    // Save file verification settings
    const saveFileVerificationSettings = async (settings) => {
        try {
            if (typeof chrome === 'undefined' || !chrome.storage) {
                console.log('Chrome storage API not available (running in browser)');
                return false;
            }
            await chrome.storage.local.set({fileVerificationSettings: settings});
            console.log('File verification settings saved.');
            return true;
        } catch (error) {
            console.error('Error saving file verification settings:', error);
            return false;
        }
    };

    // Load file verification settings
    const loadFileVerificationSettings = async () => {
        try {
            if (typeof chrome === 'undefined' || !chrome.storage) {
                console.log('Chrome storage API not available (running in browser)');
                return defaultFileVerificationSettings;
            }
            const result = await chrome.storage.local.get(['fileVerificationSettings']);
            return result.fileVerificationSettings || defaultFileVerificationSettings;
        } catch (error) {
            console.error('Error loading file verification settings:', error);
            return defaultFileVerificationSettings;
        }
    };

    // Current file verification settings state
    let currentFileVerificationSettings = {...defaultFileVerificationSettings};

    // Initialize file verification UI
    const initFileVerification = async () => {
        const enableCheckbox = document.getElementById('enableFileVerification');
        const settingsDiv = document.getElementById('fileVerificationSettings');
        const md5Checkbox = document.getElementById('enableMD5');
        const sha1Checkbox = document.getElementById('enableSHA1');
        const sha256Checkbox = document.getElementById('enableSHA256');
        const sizeCheckbox = document.getElementById('enableSizeCheck');
        const warnRadio = document.getElementById('actionWarn');
        const blockRadio = document.getElementById('actionBlock');
        const retryRadio = document.getElementById('actionRetry');
        const timeoutInput = document.getElementById('verificationTimeout');
        const logsCheckbox = document.getElementById('enableVerificationLogs');
        const autoVerifyCheckbox = document.getElementById('autoVerifyLargeFiles');
        const saveButton = document.getElementById('saveFileVerification');
        const resetButton = document.getElementById('resetFileVerification');

        if (!enableCheckbox || !settingsDiv) return;

        // Load current settings
        currentFileVerificationSettings = await loadFileVerificationSettings();

        // Set initial state
        enableCheckbox.checked = currentFileVerificationSettings.enabled;
        settingsDiv.style.display = currentFileVerificationSettings.enabled ? 'block' : 'none';

        // Set verification types
        if (md5Checkbox) md5Checkbox.checked = currentFileVerificationSettings.verificationTypes.md5;
        if (sha1Checkbox) sha1Checkbox.checked = currentFileVerificationSettings.verificationTypes.sha1;
        if (sha256Checkbox) sha256Checkbox.checked = currentFileVerificationSettings.verificationTypes.sha256;
        if (sizeCheckbox) sizeCheckbox.checked = currentFileVerificationSettings.verificationTypes.sizeCheck;

        // Set failure action
        if (warnRadio && currentFileVerificationSettings.failureAction === 'warn') warnRadio.checked = true;
        if (blockRadio && currentFileVerificationSettings.failureAction === 'block') blockRadio.checked = true;
        if (retryRadio && currentFileVerificationSettings.failureAction === 'retry') retryRadio.checked = true;

        // Set advanced settings
        if (timeoutInput) timeoutInput.value = currentFileVerificationSettings.timeout;
        if (logsCheckbox) logsCheckbox.checked = currentFileVerificationSettings.enableLogs;
        if (autoVerifyCheckbox) autoVerifyCheckbox.checked = currentFileVerificationSettings.autoVerifyLargeFiles;

        // Enable/disable toggle
        enableCheckbox.addEventListener('change', () => {
            currentFileVerificationSettings.enabled = enableCheckbox.checked;
            settingsDiv.style.display = currentFileVerificationSettings.enabled ? 'block' : 'none';
        });

        // Save settings
        if (saveButton) {
            saveButton.addEventListener('click', async () => {
                // Update settings from UI
                currentFileVerificationSettings.verificationTypes = {
                    md5: md5Checkbox ? md5Checkbox.checked : false,
                    sha1: sha1Checkbox ? sha1Checkbox.checked : false,
                    sha256: sha256Checkbox ? sha256Checkbox.checked : false,
                    sizeCheck: sizeCheckbox ? sizeCheckbox.checked : false
                };

                // Get selected failure action
                if (warnRadio && warnRadio.checked) currentFileVerificationSettings.failureAction = 'warn';
                if (blockRadio && blockRadio.checked) currentFileVerificationSettings.failureAction = 'block';
                if (retryRadio && retryRadio.checked) currentFileVerificationSettings.failureAction = 'retry';

                // Update advanced settings
                if (timeoutInput) {
                    const timeout = parseInt(timeoutInput.value);
                    currentFileVerificationSettings.timeout = (timeout >= 5 && timeout <= 300) ? timeout : 30;
                }
                if (logsCheckbox) currentFileVerificationSettings.enableLogs = logsCheckbox.checked;
                if (autoVerifyCheckbox) currentFileVerificationSettings.autoVerifyLargeFiles = autoVerifyCheckbox.checked;

                const saved = await saveFileVerificationSettings(currentFileVerificationSettings);
                if (saved) {
                    alert('File verification settings saved successfully!');
                } else {
                    alert('Failed to save settings (Chrome extension API not available).');
                }
            });
        }

        // Reset to default
        if (resetButton) {
            resetButton.addEventListener('click', () => {
                if (confirm('Are you sure you want to reset file verification settings to default?')) {
                    currentFileVerificationSettings = {...defaultFileVerificationSettings};

                    // Update UI
                    enableCheckbox.checked = currentFileVerificationSettings.enabled;
                    settingsDiv.style.display = currentFileVerificationSettings.enabled ? 'block' : 'none';

                    if (md5Checkbox) md5Checkbox.checked = currentFileVerificationSettings.verificationTypes.md5;
                    if (sha1Checkbox) sha1Checkbox.checked = currentFileVerificationSettings.verificationTypes.sha1;
                    if (sha256Checkbox) sha256Checkbox.checked = currentFileVerificationSettings.verificationTypes.sha256;
                    if (sizeCheckbox) sizeCheckbox.checked = currentFileVerificationSettings.verificationTypes.sizeCheck;

                    if (warnRadio) warnRadio.checked = currentFileVerificationSettings.failureAction === 'warn';
                    if (blockRadio) blockRadio.checked = currentFileVerificationSettings.failureAction === 'block';
                    if (retryRadio) retryRadio.checked = currentFileVerificationSettings.failureAction === 'retry';

                    if (timeoutInput) timeoutInput.value = currentFileVerificationSettings.timeout;
                    if (logsCheckbox) logsCheckbox.checked = currentFileVerificationSettings.enableLogs;
                    if (autoVerifyCheckbox) autoVerifyCheckbox.checked = currentFileVerificationSettings.autoVerifyLargeFiles;
                }
            });
        }
    };

    // Initialize file verification when DOM is ready
    initFileVerification();

    // ===== Custom Request Headers Functionality =====

    // Default custom headers settings
    const defaultCustomHeadersSettings = {
        enabled: false,
        globalHeaders: [],
        domainHeaders: [],
        headerTemplates: {
            'user-agent-chrome': {
                name: 'User-Agent',
                value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
            },
            'user-agent-firefox': {
                name: 'User-Agent',
                value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0'
            },
            'user-agent-safari': {
                name: 'User-Agent',
                value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15'
            },
            'referer': {
                name: 'Referer',
                value: 'https://www.google.com/'
            },
            'authorization-bearer': {
                name: 'Authorization',
                value: 'Bearer YOUR_TOKEN_HERE'
            },
            'authorization-basic': {
                name: 'Authorization',
                value: 'Basic YOUR_CREDENTIALS_HERE'
            },
            'accept-json': {
                name: 'Accept',
                value: 'application/json, text/plain, */*'
            },
            'content-type-json': {
                name: 'Content-Type',
                value: 'application/json'
            },
            'x-requested-with': {
                name: 'X-Requested-With',
                value: 'XMLHttpRequest'
            }
        }
    };

    // Save custom headers settings
    const saveCustomHeadersSettings = async (settings) => {
        try {
            if (typeof chrome === 'undefined' || !chrome.storage) {
                console.log('Chrome storage API not available (running in browser)');
                return false;
            }
            await chrome.storage.local.set({customHeadersSettings: settings});
            console.log('Custom headers settings saved.');
            return true;
        } catch (error) {
            console.error('Error saving custom headers settings:', error);
            return false;
        }
    };

    // Load custom headers settings
    const loadCustomHeadersSettings = async () => {
        try {
            if (typeof chrome === 'undefined' || !chrome.storage) {
                console.log('Chrome storage API not available (running in browser)');
                return defaultCustomHeadersSettings;
            }
            const result = await chrome.storage.local.get(['customHeadersSettings']);
            return result.customHeadersSettings || defaultCustomHeadersSettings;
        } catch (error) {
            console.error('Error loading custom headers settings:', error);
            return defaultCustomHeadersSettings;
        }
    };

    // Current custom headers settings state
    let currentCustomHeadersSettings = {...defaultCustomHeadersSettings};

    // Create global header item element
    const createGlobalHeaderItem = (header, index) => {
        const headerDiv = document.createElement('div');
        headerDiv.className = 'header-item';
        headerDiv.innerHTML = `
      <div class="header-info">
        <span class="header-name">${header.name}:</span>
        <span class="header-value">${header.value}</span>
        <label class="header-toggle">
          <input type="checkbox" ${header.enabled !== false ? 'checked' : ''} 
                 onchange="toggleGlobalHeader(${index}, this.checked)">
          Enabled
        </label>
      </div>
      <button onclick="removeGlobalHeader(${index})" class="remove-btn">Remove</button>
    `;
        return headerDiv;
    };

    // Create domain header item element
    const createDomainHeaderItem = (domainHeader, index) => {
        const headerDiv = document.createElement('div');
        headerDiv.className = 'domain-header-item';
        headerDiv.innerHTML = `
      <div class="domain-header-info">
        <span class="domain-pattern">${domainHeader.domain}</span>
        <span class="header-name">${domainHeader.name}:</span>
        <span class="header-value">${domainHeader.value}</span>
        <label class="header-toggle">
          <input type="checkbox" ${domainHeader.enabled !== false ? 'checked' : ''} 
                 onchange="toggleDomainHeader(${index}, this.checked)">
          Enabled
        </label>
      </div>
      <button onclick="removeDomainHeader(${index})" class="remove-btn">Remove</button>
    `;
        return headerDiv;
    };

    // Render global headers
    const renderGlobalHeaders = () => {
        const container = document.getElementById('globalHeaders');
        if (!container) return;

        container.innerHTML = '';
        currentCustomHeadersSettings.globalHeaders.forEach((header, index) => {
            container.appendChild(createGlobalHeaderItem(header, index));
        });
    };

    // Render domain headers
    const renderDomainHeaders = () => {
        const container = document.getElementById('domainHeaders');
        if (!container) return;

        container.innerHTML = '';
        currentCustomHeadersSettings.domainHeaders.forEach((domainHeader, index) => {
            container.appendChild(createDomainHeaderItem(domainHeader, index));
        });
    };

    // Global functions for header management
    window.removeGlobalHeader = (index) => {
        if (confirm('Are you sure you want to remove this header?')) {
            currentCustomHeadersSettings.globalHeaders.splice(index, 1);
            renderGlobalHeaders();
        }
    };

    window.toggleGlobalHeader = (index, enabled) => {
        if (currentCustomHeadersSettings.globalHeaders[index]) {
            currentCustomHeadersSettings.globalHeaders[index].enabled = enabled;
        }
    };

    window.removeDomainHeader = (index) => {
        if (confirm('Are you sure you want to remove this domain header?')) {
            currentCustomHeadersSettings.domainHeaders.splice(index, 1);
            renderDomainHeaders();
        }
    };

    window.toggleDomainHeader = (index, enabled) => {
        if (currentCustomHeadersSettings.domainHeaders[index]) {
            currentCustomHeadersSettings.domainHeaders[index].enabled = enabled;
        }
    };

    // Initialize custom headers UI
    const initCustomHeaders = async () => {
        const enableCheckbox = document.getElementById('enableCustomHeaders');
        const settingsDiv = document.getElementById('customHeadersSettings');
        const addGlobalHeaderBtn = document.getElementById('addGlobalHeader');
        const addDomainHeaderBtn = document.getElementById('addDomainHeader');
        const applyTemplateBtn = document.getElementById('applyTemplate');
        const exportBtn = document.getElementById('exportHeaders');
        const importBtn = document.getElementById('importHeaders');
        const importFile = document.getElementById('importHeadersFile');
        const saveBtn = document.getElementById('saveCustomHeaders');
        const resetBtn = document.getElementById('resetCustomHeaders');

        if (!enableCheckbox || !settingsDiv) return;

        // Load current settings
        currentCustomHeadersSettings = await loadCustomHeadersSettings();

        // Set initial state
        enableCheckbox.checked = currentCustomHeadersSettings.enabled;
        settingsDiv.style.display = currentCustomHeadersSettings.enabled ? 'block' : 'none';

        // Render headers
        renderGlobalHeaders();
        renderDomainHeaders();

        // Enable/disable toggle
        enableCheckbox.addEventListener('change', () => {
            currentCustomHeadersSettings.enabled = enableCheckbox.checked;
            settingsDiv.style.display = currentCustomHeadersSettings.enabled ? 'block' : 'none';
        });

        // Add global header
        if (addGlobalHeaderBtn) {
            addGlobalHeaderBtn.addEventListener('click', () => {
                const nameInput = document.getElementById('newGlobalHeaderName');
                const valueInput = document.getElementById('newGlobalHeaderValue');

                if (nameInput && valueInput && nameInput.value.trim() && valueInput.value.trim()) {
                    const newHeader = {
                        name: nameInput.value.trim(),
                        value: valueInput.value.trim(),
                        enabled: true
                    };

                    currentCustomHeadersSettings.globalHeaders.push(newHeader);
                    renderGlobalHeaders();

                    nameInput.value = '';
                    valueInput.value = '';
                } else {
                    alert('Please enter both header name and value.');
                }
            });
        }

        // Add domain header
        if (addDomainHeaderBtn) {
            addDomainHeaderBtn.addEventListener('click', () => {
                const domainInput = document.getElementById('newDomainPattern');
                const nameInput = document.getElementById('newDomainHeaderName');
                const valueInput = document.getElementById('newDomainHeaderValue');

                if (domainInput && nameInput && valueInput &&
                    domainInput.value.trim() && nameInput.value.trim() && valueInput.value.trim()) {
                    const newDomainHeader = {
                        domain: domainInput.value.trim(),
                        name: nameInput.value.trim(),
                        value: valueInput.value.trim(),
                        enabled: true
                    };

                    currentCustomHeadersSettings.domainHeaders.push(newDomainHeader);
                    renderDomainHeaders();

                    domainInput.value = '';
                    nameInput.value = '';
                    valueInput.value = '';
                } else {
                    alert('Please enter domain pattern, header name, and value.');
                }
            });
        }

        // Apply template
        if (applyTemplateBtn) {
            applyTemplateBtn.addEventListener('click', () => {
                const templateSelect = document.getElementById('headerTemplate');
                const templateKey = templateSelect.value;

                if (templateKey && currentCustomHeadersSettings.headerTemplates[templateKey]) {
                    const template = currentCustomHeadersSettings.headerTemplates[templateKey];
                    const nameInput = document.getElementById('newGlobalHeaderName');
                    const valueInput = document.getElementById('newGlobalHeaderValue');

                    if (nameInput && valueInput) {
                        nameInput.value = template.name;
                        valueInput.value = template.value;
                    }
                }
            });
        }

        // Export headers
        if (exportBtn) {
            exportBtn.addEventListener('click', () => {
                const exportData = {
                    globalHeaders: currentCustomHeadersSettings.globalHeaders,
                    domainHeaders: currentCustomHeadersSettings.domainHeaders,
                    exportDate: new Date().toISOString()
                };

                const blob = new Blob([JSON.stringify(exportData, null, 2)], {type: 'application/json'});
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'swiftshadow-headers.json';
                a.click();
                URL.revokeObjectURL(url);
            });
        }

        // Import headers
        if (importBtn && importFile) {
            importBtn.addEventListener('click', () => {
                importFile.click();
            });

            importFile.addEventListener('change', (event) => {
                const file = event.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        try {
                            const importData = JSON.parse(e.target.result);

                            if (importData.globalHeaders && Array.isArray(importData.globalHeaders)) {
                                currentCustomHeadersSettings.globalHeaders = importData.globalHeaders;
                                renderGlobalHeaders();
                            }

                            if (importData.domainHeaders && Array.isArray(importData.domainHeaders)) {
                                currentCustomHeadersSettings.domainHeaders = importData.domainHeaders;
                                renderDomainHeaders();
                            }

                            alert('Headers imported successfully!');
                        } catch (error) {
                            alert('Error importing headers: Invalid JSON format.');
                        }
                    };
                    reader.readAsText(file);
                }
            });
        }

        // Save settings
        if (saveBtn) {
            saveBtn.addEventListener('click', async () => {
                const saved = await saveCustomHeadersSettings(currentCustomHeadersSettings);
                if (saved) {
                    alert('Custom headers settings saved successfully!');
                } else {
                    alert('Failed to save settings (Chrome extension API not available).');
                }
            });
        }

        // Reset to default
        if (resetBtn) {
            resetBtn.addEventListener('click', () => {
                if (confirm('Are you sure you want to reset custom headers settings to default?')) {
                    currentCustomHeadersSettings = {...defaultCustomHeadersSettings};

                    // Update UI
                    enableCheckbox.checked = currentCustomHeadersSettings.enabled;
                    settingsDiv.style.display = currentCustomHeadersSettings.enabled ? 'block' : 'none';

                    renderGlobalHeaders();
                    renderDomainHeaders();
                }
            });
        }
    };

    // Initialize custom headers when DOM is ready
    initCustomHeaders();
});